from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.models.work_order import WorkOrder
from app.models.process_record import ProcessRecord
from app.models.user import User
from app.models import db
from .work_orders_utils import (
    get_current_user, handle_db_error, 
    validate_work_order_permission
)
from app.utils.auth import require_permission
from datetime import datetime

work_orders_process_bp = Blueprint('work_orders_process', __name__)

@work_orders_process_bp.route('/<int:work_order_id>/process-records', methods=['GET'])
@jwt_required()
@require_permission('work_order.view', 'work_order.edit')
def get_process_records(work_order_id):
    """获取工单处理记录"""
    try:
        current_user = get_current_user()
        work_order = WorkOrder.query.get_or_404(work_order_id)
        
        # 权限检查
        if not validate_work_order_permission(work_order, current_user, "view"):
            return jsonify({'error': '权限不足'}), 403
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = min(request.args.get('per_page', 20, type=int), 100)
        action_type = request.args.get('action_type')
        user_id = request.args.get('user_id', type=int)
        
        # 构建查询
        query = ProcessRecord.query.filter_by(work_order_id=work_order_id)
        
        # 应用过滤条件
        if action_type:
            query = query.filter(ProcessRecord.action == action_type)
        if user_id:
            query = query.filter(ProcessRecord.operator_id == user_id)
        
        # 排序（最新的在前）
        query = query.order_by(ProcessRecord.created_at.desc())
        
        # 分页
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 构建返回数据
        records = []
        for record in pagination.items:
            record_dict = record.to_dict()
            
            # 添加用户信息
            if record.operator:
                record_dict['user'] = {
                    'id': record.operator.id,
                    'username': record.operator.username,
                    'name': record.operator.name
                }
            
            records.append(record_dict)
        
        return jsonify({
            'process_records': records,
            'pagination': {
                'page': pagination.page,
                'pages': pagination.pages,
                'per_page': pagination.per_page,
                'total': pagination.total,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            }
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_process_bp.route('/<int:work_order_id>/process-records', methods=['POST'])
@jwt_required()
@require_permission('work_order.edit')
@handle_db_error("创建处理记录")
def create_process_record(work_order_id):
    """创建工单处理记录"""
    current_user = get_current_user()
    work_order = WorkOrder.query.get_or_404(work_order_id)
    data = request.get_json()
    
    if not data:
        return jsonify({'error': '未收到请求数据'}), 400
    
    # 权限检查
    if not validate_work_order_permission(work_order, current_user, "update"):
        return jsonify({'error': '权限不足'}), 403
    
    # 验证必填字段
    if not data.get('action'):
        return jsonify({'error': '操作类型不能为空'}), 400
    
    if not data.get('description'):
        return jsonify({'error': '描述不能为空'}), 400
    
    # 创建处理记录
    process_record = ProcessRecord(
        work_order_id=work_order_id,
        operator_id=current_user.id,
        action=data['action'],
        description=data['description'],
        created_at=datetime.utcnow()
    )
    
    db.session.add(process_record)
    
    # 如果是状态变更，同时更新工单状态
    if data.get('update_status'):
        new_status = data.get('new_status')
        if new_status and new_status != work_order.status:
            old_status = work_order.status
            work_order.status = new_status
            work_order.updated_at = datetime.utcnow()
            
            # 创建状态变更记录
            status_record = ProcessRecord(
                work_order_id=work_order_id,
                operator_id=current_user.id,
                action='状态变更',
                description=f'工单状态从 {old_status} 变更为 {new_status}',
                created_at=datetime.utcnow()
            )
            db.session.add(status_record)
    
    db.session.commit()
    
    return jsonify({
        'process_record': process_record.to_dict(),
        'message': '处理记录创建成功'
    }), 201

@work_orders_process_bp.route('/process-records/<int:record_id>', methods=['PUT'])
@jwt_required()
@require_permission('work_order.edit')
@handle_db_error("更新处理记录")
def update_process_record(record_id):
    """更新处理记录"""
    current_user = get_current_user()
    process_record = ProcessRecord.query.get_or_404(record_id)
    work_order = WorkOrder.query.get_or_404(process_record.work_order_id)
    data = request.get_json()
    
    if not data:
        return jsonify({'error': '未收到请求数据'}), 400
    
    # 权限检查：只有记录创建者、管理员或工单相关人员可以修改
    if (current_user.role not in ['admin', 'manager'] and 
        process_record.operator_id != current_user.id and
        not validate_work_order_permission(work_order, current_user, "update")):
        return jsonify({'error': '权限不足'}), 403
    
    # 更新字段
    updatable_fields = ['action', 'description', 'notes']
    for field in updatable_fields:
        if field in data:
            setattr(process_record, field, data[field])
    
    process_record.updated_at = datetime.utcnow()
    db.session.commit()
    
    return jsonify({
        'process_record': process_record.to_dict(),
        'message': '处理记录更新成功'
    }), 200

@work_orders_process_bp.route('/process-records/<int:record_id>', methods=['DELETE'])
@jwt_required()
@require_permission('work_order.delete')
@handle_db_error("删除处理记录")
def delete_process_record(record_id):
    """删除处理记录（仅管理员）"""
    process_record = ProcessRecord.query.get_or_404(record_id)
    
    db.session.delete(process_record)
    db.session.commit()
    
    return jsonify({'message': '处理记录删除成功'}), 200

@work_orders_process_bp.route('/<int:work_order_id>/timeline', methods=['GET'])
@jwt_required()
@require_permission('work_order.view', 'work_order.edit')
def get_work_order_timeline(work_order_id):
    """获取工单时间线（包含处理记录和状态变更）"""
    try:
        current_user = get_current_user()
        work_order = WorkOrder.query.get_or_404(work_order_id)
        
        # 权限检查
        if not validate_work_order_permission(work_order, current_user, "view"):
            return jsonify({'error': '权限不足'}), 403
        
        # 获取所有处理记录
        process_records = ProcessRecord.query.filter_by(
            work_order_id=work_order_id
        ).order_by(ProcessRecord.created_at.asc()).all()
        
        # 构建时间线数据
        timeline = []
        
        # 添加工单创建事件
        timeline.append({
            'id': f'created_{work_order.id}',
            'type': 'created',
            'action': '工单创建',
            'description': f'工单 {work_order.work_order_number} 创建',
            'user': {
                'id': work_order.creator.id,
                'username': work_order.creator.username,
                'name': work_order.creator.name
            } if work_order.creator else None,
            'timestamp': work_order.created_at.isoformat(),
            'details': {
                'title': work_order.title,
                'priority': work_order.priority,
                'status': work_order.status
            }
        })
        
        # 添加处理记录
        for record in process_records:
            timeline.append({
                'id': record.id,
                'type': 'process',
                'action': record.action,
                'description': record.description,
                'notes': record.notes,
                'user': {
                    'id': record.operator.id,
                    'username': record.operator.username,
                    'name': record.operator.name
                } if record.operator else None,
                'timestamp': record.created_at.isoformat()
            })
        
        # 如果工单已完成，添加完成事件
        if work_order.status == 'completed' and work_order.updated_at:
            timeline.append({
                'id': f'completed_{work_order.id}',
                'type': 'completed',
                'action': '工单完成',
                'description': f'工单 {work_order.work_order_number} 已完成',
                'timestamp': work_order.updated_at.isoformat()
            })
        
        # 按时间排序
        timeline.sort(key=lambda x: x['timestamp'])
        
        return jsonify({
            'timeline': timeline,
            'work_order': {
                'id': work_order.id,
                'work_order_number': work_order.work_order_number,
                'title': work_order.title,
                'status': work_order.status
            }
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_process_bp.route('/process-records/actions', methods=['GET'])
@jwt_required()
@require_permission('work_order.view', 'work_order.edit')
def get_available_actions():
    """获取可用的处理记录操作类型"""
    try:
        # 预定义的操作类型
        actions = [
            {'value': '接单', 'label': '接单', 'description': '接受工单任务'},
            {'value': '开始处理', 'label': '开始处理', 'description': '开始处理工单'},
            {'value': '暂停处理', 'label': '暂停处理', 'description': '暂停工单处理'},
            {'value': '继续处理', 'label': '继续处理', 'description': '继续处理工单'},
            {'value': '完成处理', 'label': '完成处理', 'description': '完成工单处理'},
            {'value': '转派', 'label': '转派', 'description': '将工单转派给其他人'},
            {'value': '退回', 'label': '退回', 'description': '退回工单'},
            {'value': '取消', 'label': '取消', 'description': '取消工单'},
            {'value': '备注', 'label': '添加备注', 'description': '添加处理备注'},
            {'value': '材料录入', 'label': '材料录入', 'description': '录入使用的材料'},
            {'value': '状态变更', 'label': '状态变更', 'description': '变更工单状态'},
            {'value': '其他', 'label': '其他', 'description': '其他操作'}
        ]
        
        return jsonify({
            'actions': actions
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_process_bp.route('/<int:work_order_id>/quick-actions', methods=['POST'])
@jwt_required()
@require_permission('work_order.edit')
@handle_db_error("快速操作")
def quick_action(work_order_id):
    """快速操作（接单、开始处理、完成等）"""
    current_user = get_current_user()
    work_order = WorkOrder.query.get_or_404(work_order_id)
    data = request.get_json()
    
    if not data or not data.get('action'):
        return jsonify({'error': '操作类型不能为空'}), 400
    
    action = data['action']
    
    # 权限检查
    if not validate_work_order_permission(work_order, current_user, "update"):
        return jsonify({'error': '权限不足'}), 403
    
    # 执行快速操作
    if action == 'accept':
        # 接单
        if work_order.assignee_id and work_order.assignee_id != current_user.id:
            return jsonify({'error': '工单已被其他人接受'}), 400
        
        work_order.assignee_id = current_user.id
        work_order.status = 'assigned'
        description = f'{current_user.name} 接受了工单'
        
    elif action == 'start':
        # 开始处理
        if work_order.status not in ['pending', 'assigned']:
            return jsonify({'error': '当前状态不允许开始处理'}), 400
        
        work_order.status = 'in_progress'
        description = f'{current_user.name} 开始处理工单'
        
    elif action == 'complete':
        # 完成
        if work_order.status != 'in_progress':
            return jsonify({'error': '当前状态不允许完成'}), 400
        
        work_order.status = 'completed'
        description = f'{current_user.name} 完成了工单'
        
    elif action == 'cancel':
        # 取消
        if work_order.status == 'completed':
            return jsonify({'error': '已完成的工单不能取消'}), 400
        
        work_order.status = 'cancelled'
        description = f'{current_user.name} 取消了工单'
        
    else:
        return jsonify({'error': '不支持的操作类型'}), 400
    
    # 更新工单
    work_order.updated_at = datetime.utcnow()
    
    # 创建处理记录
    process_record = ProcessRecord(
        work_order_id=work_order_id,
        operator_id=current_user.id,
        action=action,
        description=description,
        created_at=datetime.utcnow()
    )
    
    db.session.add(process_record)
    db.session.commit()
    
    return jsonify({
        'work_order': work_order.to_dict(),
        'process_record': process_record.to_dict(),
        'message': f'操作 {action} 执行成功'
    }), 200